package client.lobby;

import java.io.IOException;
import java.io.ObjectInputStream;


import shared.messages.StartMessage;
import shared.player.Player;
import client.gui.ErrorMessageGui;

/**StartListener - waits for a start message
 * and distributes player objects
 */
public class StartListener extends Thread {
	
	/** The waiting lobby. */
	WaitingLobby lobby;
	
	/** The object which is used to store a incoming message. */
	Object in;
	
	/** The name of the player. */
	String name;
	
	/** Traffic in. */
	ObjectInputStream netIn;

	/**
	 * Instantiates a new start listener.
	 *
	 * @param netIn the traffic in
	 * @param lobby the waiting lobby
	 * @param name the name of the player
	 */
	public StartListener(ObjectInputStream netIn, WaitingLobby lobby, String name) {
		this.name = name;
		this.lobby = lobby;
		this.netIn = netIn;
		start();
	}

	/**waits for a start message and distributes the player objects
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		while (true) {
			try {
				in = netIn.readObject();
			} catch (ClassNotFoundException e) {
				new ErrorMessageGui("Object class was not found.");
				break;
			} catch (IOException e) {
				new ErrorMessageGui("Error reading from server. Server closed or connection dropped.");
				break;
			}
			if (in != null && in instanceof StartMessage) {
				Player p1 = ((StartMessage) in).p1;
				Player p2 = ((StartMessage) in).p2;
				Player p3 = ((StartMessage) in).p3;
				if (p1.name.equals(name)) {
					lobby.setPlayer(p1);
					lobby.setOpp1(p2);
					lobby.setOpp2(p3);
				} else if (p2.name.equals(name)) {
					lobby.setPlayer(p2);
					lobby.setOpp1(p1);
					lobby.setOpp2(p3);
				} else if (p3.name.equals(name)) {
					lobby.setPlayer(p3);
					lobby.setOpp1(p1);
					lobby.setOpp2(p2);
				}
				lobby.setGame();
				break;
			}
		}
	}
}
